package cn.itcast.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
@WebServlet("/ServletDemo01")
public class ServletDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.通过响应对象写出提示信息
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("欢迎访问本网站，您的最后访问时间为：<br>");
//        创建cookie对象
        Cookie cookie = new Cookie("time",System.currentTimeMillis() + "");
//        设置最大存活时间
        cookie.setMaxAge(3600);
//        将cookie对象响应到客户端
        resp.addCookie(cookie);
//        获取cookie
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie1 : cookies) {
            if ("time".equals(cookie1.getName())) {
//                6.获取cookie对象中的value值 进行写出
                String value = cookie1.getValue();
                SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
//                String format = sdf.format(new Date(Long.parseLong(value)));
                resp.getWriter().write(sdf.format(new Date(Long.parseLong(value))));
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
